package com.vivi.codereview.actors;

import java.io.File;
import java.util.Set;

import com.vivi.codereview.tools.Log;

/**
 * Main of this actor is only to remove the hijack status of files related to
 * one AgileReview project, in case an error occurred or when the program has
 * been wrongly closed before end of the code review. Indeed, otherwise, since
 * we have some checks to ensure we don't start a code review when impacted
 * files or not read-only, we will be blocked otherwise and we will have to undo
 * hijack manually.
 *
 * @author vivi
 *
 */
public class UnhijackerActor extends AgileReviewerActor {

	@Override
	public int process() throws Exception {
		Log.logSeparator();
		// We look for jdevcc folder
		String jdevccFolder = getRootDirectory();
		String reviewFolder = selectFolder(REVIEW_FOLDER,
		        "Please select the Review project you want to use (mandatory step):");
		File zippedFile = getZippedFile(reviewFolder, ZIP_FILENAME);
		// we get the folder (stream) we want to use
		String rootStream = selectFolder(jdevccFolder,
		        "Please select index of stream you want to use in list above (mandatory step):");
		String logFile = getZipUtil().readFileInZip(zippedFile, ZIP_LOG_FILENAME);
		Set<String> files = getFilesFromLog(rootStream, logFile);
		// We know all files are available now - no checkout, no hijack
		unHijackFiles(rootStream, files);
		return Log.Exit.OK;
	}

	/**
	 * We don' ask what user wants to do since we know he wants to undo hijack
	 * for all files.
	 */
	protected void unHijackFiles(String root, Set<String> files) throws Exception {
		Log.log("We undo hijacks", Log.D);
		for (String file : files) {
		  Log.log("We force update"+file, Log.D);
		  getCcUtil().updateFile(root, file);
		  File realFile = getSysUtil().getFile(root, file);
		  if (realFile.canWrite()) {
		    Log.log("We can write an updated file,  that means it was not in the source control, we can delete it " + file, Log.D);
		    realFile.delete();
		    Log.log(file + " has been deleted.", Log.I);
		  }
		}
	}

	@Override
	public String getName() {
		return "Unhijacker";
	}

}
